import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'sqlite_util.dart';

class MainManager with ChangeNotifier {
  static MainManager instance = MainManager();
  List likeList = [];
  final sqliteUtil = SqliteUtil();

  void init() async {
    sqliteUtil.createDb(1);
    // clearDb();
    refresh();
  }

  Future queryAll() async {
    return query("select * from RecipeLike");
  }

  void clearDb() {
    sqliteUtil.delete("DELETE FROM RecipeLike");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  bool isOutside(recipe) {
    return likeList.every(
        (item) => item['recipeId'].toString() != recipe['recipeId'].toString());
  }

  void like(recipe) async {
    if (isOutside(recipe)) {
      likeList.add(recipe);
    } else {
      likeList.removeWhere((item) =>
          item['recipeId'].toString() == recipe['recipeId'].toString());
    }
    update(likeList);
    refresh();
  }

  void insert(likeList) async {
    await sqliteUtil.insert(
        'INSERT INTO RecipeLike(id,likeList) VALUES("1","${json.encode(likeList)}")');
    refresh();
  }

  void update(likeList) async {
    if (likeList.length > 10) likeList.removeLast();
    await sqliteUtil.update('UPDATE RecipeLike SET likeList = ? WHERE id = "1"',
        [json.encode(likeList)]);
    refresh();
  }

  void delete() async {
    await sqliteUtil.delete('DELETE FROM RecipeLike WHERE id = "1"');
    refresh();
  }

  refresh() {
    queryAll().then((res) {
      if (res.length == 0) {
        insert([]);
        likeList = [];
        notifyListeners();
      } else {
        likeList = json.decode(res[0]['likeList']);
        notifyListeners();
      }
    });
  }
}
